package com.cqq.auth.shiro;

import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.NamedFilterList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cqq.auth.service.PermResourceService;
import com.cqq.auth.service.bean.PermissionBean;
import com.cqq.auth.service.bean.UrlBean;

import javax.annotation.PostConstruct;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class ShiroFilerChainManager {

	private static final Logger log = LoggerFactory.getLogger(ShiroFilerChainManager.class);
	
	private DefaultFilterChainManager filterChainManager;

	private String systemCode;
	
	private PermResourceService permResourceService;
	
	private Map<String, NamedFilterList> defaultFilterChains;

	public DefaultFilterChainManager getFilterChainManager() {
		return filterChainManager;
	}

	public void setFilterChainManager(DefaultFilterChainManager filterChainManager) {
		this.filterChainManager = filterChainManager;
	}
	
	public void setSystemCode(String systemCode) {
		this.systemCode = systemCode;
	}

	public void setPermResourceService(PermResourceService permResourceService) {
		this.permResourceService = permResourceService;
	}

	@PostConstruct
	public void init() {
		defaultFilterChains = new LinkedHashMap<String, NamedFilterList>();
		defaultFilterChains.putAll(filterChainManager.getFilterChains());
		filterChainManager.getFilterChains().clear();
		
		log.debug("init shiro filer chain ...");
		List<UrlBean> urls=this.permResourceService.listAllUrl(systemCode);
		StringBuffer sb=new StringBuffer();
		String perms=null;
		for(UrlBean url:urls){
			if(url.getPerms()==null || url.getPerms().isEmpty()){
				continue;
			}
			sb.setLength(0);
			for(PermissionBean perm:url.getPerms()){
				sb.append(perm.getCode()).append(",");
			}
			perms=sb.substring(0,sb.length()-1);
			filterChainManager.addToChain(url.getUrl(), "perms", perms);
			log.debug("addToChain: [{}] [{}]",url.getUrl(),perms);
		}
		filterChainManager.getFilterChains().putAll(defaultFilterChains);
	}

}
